import 'package:animated_flip_counter/animated_flip_counter.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/http_constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/constant/status_constant.dart';
import 'package:distribution_mall_flutter/entity/goods/detail/goods_detail_entity.dart';
import 'package:distribution_mall_flutter/entity/goods/goods.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/goods/checkout/domain/checkout_pass_params.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/product_details_provider.dart';
import 'package:distribution_mall_flutter/pages/goods/checkout/modal_check.dart';
import 'package:distribution_mall_flutter/provider/goods/product_details.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/router/route_utils.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:getwidget/getwidget.dart';
import 'package:webview_flutter/webview_flutter.dart';

class ProductFooter extends ConsumerStatefulWidget {
  final String? saleItemId;

  const ProductFooter({super.key, this.saleItemId});

  @override
  ConsumerState createState() => _ProductFooter();
}

class _ProductFooter extends ConsumerState<ProductFooter> {
  WebViewController? webViewController;
  String url = '';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      GoodsDetailEntity? detail =
          ref.watch(pDetailProvider.select((value) => value.detail));
      Map<String, String?> params = {
        'mainImage': detail?.suInfo?.mainImages?[0],
        'saleItemId': widget.saleItemId,
        ...Utils.getUserParams()
      };
      url = '${HttpConstant.service}?${Uri(queryParameters: params).query}';
      if (!kIsWeb) {
        webViewController = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..loadRequest(Uri.parse(url))
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (int progress) {},
              onPageStarted: (String url) {},
              onPageFinished: (String url) {},
              onHttpError: (HttpResponseError error) {},
              onWebResourceError: (WebResourceError error) {},
              // onNavigationRequest: (NavigationRequest request) {
              //   if (request.url.startsWith('https://www.youtube.com/')) {
              //     return NavigationDecision.prevent;
              //   }
              //   return NavigationDecision.navigate;
              // },
            ),
          )
          ..reload();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    int skuTotal = ref.watch(pDetailProvider.select((value) => value.skuTotal));
    CalculateEntity? calculatePrice =
        ref.watch(pDetailProvider.select((value) => value.calculatePrice));
    bool calLoading =
        ref.watch(pDetailProvider.select((value) => value.calLoading));
    bool isLogin = ref.watch(loginStateProvider);

    ///是否展示引导
    bool showGuide = ref.watch(productDetailsShowGuideProvider);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisSize: MainAxisSize.min,
      children: [
        if (showGuide) ...[
          GestureDetector(
            onTap: () {
              ref.read(productDetailsShowGuideProvider.notifier).closeGuide();
            },
            child: Container(
              margin: const EdgeInsets.only(right: 15),
              padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 9),
              decoration: BoxDecoration(
                color: const Color(0xFF0091F3),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: const EdgeInsets.only(right: 15),
                    child: Text(
                      S.current.productDetails_tip,
                      style: const TextStyle(fontSize: 13, color: Colors.white),
                    ),
                  ),
                  const Icon(
                    Icons.close,
                    color: Colors.white,
                    size: 16,
                  )
                ],
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(right: 60),
            child: CustomPaint(
              size: const Size(15, 7),
              painter: DownwardArrowPainter(),
            ),
          ),
        ],
        Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(0, 0, 0, 0.07),
                blurRadius: 10,
                offset: Offset(0, -0.9),
              )
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Visibility(
                  visible: skuTotal > 0,
                  child: DefaultTextStyle(
                      style: const TextStyle(
                          color: Color.fromRGBO(134, 141, 150, 1),
                          fontSize: 12.7,
                          letterSpacing: TextConstant.letterSpacing),
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(EdgeConstant.edge146),
                        decoration: const BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: ColorConstant.grey233_4,
                                    width: 0.9))),
                        // height: 63.7,
                        constraints: const BoxConstraints(
                          minHeight: 42,
                          maxHeight: 64.7,
                        ),
                        child: Wrap(
                          alignment: WrapAlignment.end,
                          runAlignment: WrapAlignment.center,
                          children: [
                            // AnimatedFlipCounter(
                            //   prefix: '${S.current.Add} ',
                            //   suffix: ' ${S.current.Items} ',
                            //   value: skuTotal,
                            // ),
                            // SizedBox(
                            //   width: 29,
                            //   child: Container(
                            //     width: 0.9,
                            //     height: 14.6,
                            //     margin: const EdgeInsets.symmetric(
                            //         horizontal: 14.1),
                            //     color: ColorConstant.grey237,
                            //   ),
                            // ),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Utils.currencyWidgetV2(
                                      calculatePrice?.totalPrice ?? '',
                                      loading: calLoading,
                                      label: '${S.current.total}: ',
                                      symbolStyle: const TextStyle(
                                          color:
                                              Color.fromRGBO(134, 141, 150, 1),
                                          fontSize: 8,
                                          letterSpacing:
                                              TextConstant.letterSpacing),
                                      commonStyle: const TextStyle(
                                          color:
                                              Color.fromRGBO(134, 141, 150, 1),
                                          fontSize: 12.7,
                                          letterSpacing:
                                              TextConstant.letterSpacing),
                                      mainAxis: MainAxisAlignment.end,
                                      textAlign: TextAlign.right,
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 2,
                                    )
                                  ],
                                ),
                                SizedBox(
                                  width: 29,
                                  child: Container(
                                    width: 0.9,
                                    height: 14.6,
                                    margin: const EdgeInsets.symmetric(
                                        horizontal: 14.1),
                                    color: ColorConstant.grey237,
                                  ),
                                ),
                                Utils.currencyWidgetV2(
                                    calculatePrice?.totalProfitPrice ?? 0,
                                    loading: calLoading,
                                    textAlign: TextAlign.right,
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                    mainAxisSize: MainAxisSize.min,
                                    label: '${S.current.potentital_profit}: ',
                                    symbolStyle: const TextStyle(
                                        color: ColorConstant.black34,
                                        fontSize: 8,
                                        letterSpacing:
                                            TextConstant.letterSpacing),
                                    commonStyle: const TextStyle(
                                        color: ColorConstant.black34,
                                        letterSpacing:
                                            TextConstant.letterSpacing,
                                        fontSize: FontConstant.f127))
                              ],
                            ),
                          ],
                        ),
                      ))),
              Padding(
                padding: EdgeInsets.fromLTRB(
                    32, 9.1, 14.6, 9.1 + MediaQuery.of(context).padding.bottom),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        Utils.go2Page(() {
                          appRouter.push(ServiceRoute(
                              webViewController: webViewController));
                        }, suffix: url, url: url);
                      },
                      child: ImageLoader.imageAsset(ImageLocalConstant.service,
                          commonWH: 24.4),
                    ),
                    SizedBox(
                      width: 264,
                      height: 43.7,
                      child: ClipRRect(
                        borderRadius:
                            const BorderRadius.all(Radius.circular(7.3)),
                        child: GFButton(
                            onPressed: isLogin
                                ? (skuTotal > 0
                                    ? (() async {
                                        final DateTime startTime =
                                            DateTime.now();
                                        Iterable<Sale> skuList =
                                            ref.read(pDetailProvider).skuList();
                                        FirebaseAnalyticsUtils.logEvent(
                                            name: PointConstant.pdBuyNow,
                                            parameters: {
                                              'saleItemId':
                                                  widget.saleItemId ?? '',
                                              'quantity': skuTotal,
                                              'spec': skuList
                                                  .map((item) => item.specInfos
                                                      ?.map((v) => v.specUnit)
                                                      .toList()
                                                      .join('/'))
                                                  .toList()
                                                  .join(',')
                                            });
                                        await EPModalBottomSheet.showCMBS(
                                            context: context,
                                            builder: (context) => ModalCheck(
                                                  checkoutPassParams:
                                                      CheckoutPassParams(
                                                    orderType: OrderTypeConstant
                                                        .normal,
                                                    skuTotal: skuTotal,
                                                    transportType: ref
                                                                .read(
                                                                    pDetailProvider)
                                                                .detail
                                                                ?.suInfo
                                                                ?.shippingInfo
                                                                ?.isLocalShipping ==
                                                            true
                                                        ? OrderTransportConstant
                                                            .local
                                                        : OrderTransportConstant
                                                            .sea,
                                                    orderGoodsList: ref
                                                        .read(pDetailProvider)
                                                        .orderItemGroupList,
                                                  ),
                                                ));
                                        RouteUtils.onStoreDialogStayTime(
                                          name: PointDialogNameConstant
                                              .pdCheckout,
                                          startTime: startTime,
                                          endTime: DateTime.now(),
                                        );
                                      })
                                    : null)
                                : () {
                                    appRouter.push(const LoginRoute());
                                  },
                            color: ColorConstant.black20,
                            borderSide: const BorderSide(
                              color: Colors.transparent,
                              width: 0.9,
                            ),
                            text: isLogin
                                ? S.current.productDetails_purchase
                                : S.current.loginIn,
                            textStyle: const TextStyle(
                                color: Colors.white,
                                letterSpacing: TextConstant.letterSpacing,
                                fontSize: 16.4,
                                fontWeight: FontWeight.bold)),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ],
    );
  }
}

class DownwardArrowPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = const Color(0xFF0091F3)
      ..strokeWidth = 2.0
      ..style = PaintingStyle.fill;

    // 绘制箭头的路径
    Path path = Path();
    path.moveTo(0, 0);
    path.lineTo(size.width / 2, size.height);
    path.lineTo(size.width, 0);
    path.lineTo(0, 0);
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
